package com.parkcar;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.alipay.sdk.app.PayTask;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;

import java.math.BigDecimal;

import HttpUtils.HttpChargeRequest;
import Modle.AliPayBean;
import Modle.PayResult;
import util.BaseActivity;
import util.BaseTools;

/**
 * Created by Administrator on 2016/1/14.
 */
public class RechargeActivity extends BaseActivity implements View.OnClickListener {
    private TextView discount_10, discount_50, discount_100, discount_200, discount_500, discount_other;
    private double moneyCount = 0;
    private HttpChargeRequest chargeRequest, chargeRequest1, chargeRequest2;
    private static final int SDK_PAY_FLAG = 1;
    private int type = 1;
    private IWXAPI api;
    private ui.AlertDialog mAertDialog;
    private ImageView ali_pay, wx_pay;
    private AliPayBean payBean;
    @Override
    protected void setUpui(Bundle arg0) {
        setContentView(R.layout.activity_recharge);
        setTitle("钱包充值");
        discount_10 = (TextView) findViewById(R.id.discount_10);
        discount_50 = (TextView) findViewById(R.id.discount_50);
        discount_100 = (TextView) findViewById(R.id.discount_100);
        discount_200 = (TextView) findViewById(R.id.discount_200);
        discount_500 = (TextView) findViewById(R.id.discount_500);
        discount_other = (TextView) findViewById(R.id.discount_other);
        ali_pay = (ImageView) findViewById(R.id.ali_pay);
        wx_pay = (ImageView) findViewById(R.id.wx_pay);
        ali_pay.setOnClickListener(this);
        wx_pay.setOnClickListener(this);
        discount_other.setOnClickListener(this);
        discount_10.setOnClickListener(this);
        discount_50.setOnClickListener(this);
        discount_100.setOnClickListener(this);
        discount_200.setOnClickListener(this);
        discount_500.setOnClickListener(this);
        api = WXAPIFactory.createWXAPI(this, "wxac2843ffa600c3d2", true);
    }

    @Override
    protected void updateUI(boolean isLogin) {

    }

    public void toCharge(View view) {
        Log.e("money", moneyCount + "");
        if (moneyCount <= 0 || moneyCount >= 10000) {
            toast("请输入有效金额：大于0元，小于1万元");
            return;
        }
        toast("正在准备支付环境");
        final BigDecimal bigDecimal = new BigDecimal(moneyCount);
        chargeRequest = new HttpChargeRequest(this, 0);
        chargeRequest.setMoney(bigDecimal, type);
        chargeRequest.setmIHttpClinetListener(this);
        chargeRequest.doRequest();
    }

    @Override
    public void httpSuccessListener(Bundle successMsg) {
        super.httpSuccessListener(successMsg);
        if (mBaseResult == null) {
            toast("与服务器失去连接");
            return;
        }
        if (chargeRequest1 != null && action.equalsIgnoreCase(chargeRequest1.getAction())) {
            if (mBaseResult.getStatus().getRetCode() == 0) {
                payBean = mBaseResult.toObject(AliPayBean.class);
                if (!BaseTools.isValueEmpty(mBaseResult.getData())) {
                    alipagy();
                }
            } else {
                toast(mBaseResult.getStatus().getMsg());
            }
        } else if (chargeRequest != null && action.equalsIgnoreCase(chargeRequest.getAction())) {
            if (mBaseResult.getStatus().getRetCode() == 0) {
                String order_title = mBaseResult.getAsJsonObject().getString("order_title");
                if (!BaseTools.isValueEmpty(order_title)) {
                    if (type == 1) {
                       doAlipayRequest(order_title);
                    } else if (type == 2) {
                        wxPay(order_title);
                    }
                }
            } else {
                toast(mBaseResult.getStatus().getMsg());
            }
        } else if (chargeRequest2 != null && action.equalsIgnoreCase(chargeRequest2.getAction())) {
            if (mBaseResult.getStatus().getRetCode() == 0) {
                toast("正在调起微信支付");
                if (!api.isWXAppInstalled()) {
                    toast("未安装微信");
                    return;
                }
                if (!api.isWXAppSupportAPI()) {
                    toast("当前版本不支持支付功能");
                    return;
                }
                PayReq req = mBaseResult.toObject(PayReq.class);
                if (BaseTools.isValueEmpty(req.packageValue)) {
                    req.packageValue = "Sign=WXPay";
                }
                api.sendReq(req);
            } else {
                toast(mBaseResult.getStatus().getMsg());
            }
        }
    }
    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.discount_10:
                moneyCount = 10;
                discount_other.setText("其他");
                discount_10.setBackgroundResource(R.drawable.recharge_bg);
                discount_50.setBackgroundResource(R.drawable.recharge);
                discount_100.setBackgroundResource(R.drawable.recharge);
                discount_200.setBackgroundResource(R.drawable.recharge);
                discount_500.setBackgroundResource(R.drawable.recharge);
                discount_other.setBackgroundResource(R.drawable.recharge);
                break;
            case R.id.discount_50:
                moneyCount = 50;
                discount_other.setText("其他");
                discount_10.setBackgroundResource(R.drawable.recharge);
                discount_50.setBackgroundResource(R.drawable.recharge_bg);
                discount_100.setBackgroundResource(R.drawable.recharge);
                discount_200.setBackgroundResource(R.drawable.recharge);
                discount_500.setBackgroundResource(R.drawable.recharge);
                discount_other.setBackgroundResource(R.drawable.recharge);
                break;
            case R.id.discount_100:
                discount_other.setText("其他");
                moneyCount = 100;
                discount_10.setBackgroundResource(R.drawable.recharge);
                discount_50.setBackgroundResource(R.drawable.recharge);
                discount_100.setBackgroundResource(R.drawable.recharge_bg);
                discount_200.setBackgroundResource(R.drawable.recharge);
                discount_500.setBackgroundResource(R.drawable.recharge);
                discount_other.setBackgroundResource(R.drawable.recharge);
                break;
            case R.id.discount_200:
                discount_other.setText("其他");
                moneyCount = 200;
                discount_10.setBackgroundResource(R.drawable.recharge);
                discount_50.setBackgroundResource(R.drawable.recharge);
                discount_100.setBackgroundResource(R.drawable.recharge);
                discount_200.setBackgroundResource(R.drawable.recharge_bg);
                discount_500.setBackgroundResource(R.drawable.recharge);
                discount_other.setBackgroundResource(R.drawable.recharge);
                break;
            case R.id.discount_500:
                discount_other.setText("其他");
                moneyCount = 500;
                discount_10.setBackgroundResource(R.drawable.recharge);
                discount_50.setBackgroundResource(R.drawable.recharge);
                discount_100.setBackgroundResource(R.drawable.recharge);
                discount_200.setBackgroundResource(R.drawable.recharge);
                discount_500.setBackgroundResource(R.drawable.recharge_bg);
                discount_other.setBackgroundResource(R.drawable.recharge);
                break;
            case R.id.discount_other:
                showDailog();
                break;
            case R.id.wx_pay:
                if (type != 2) {
                    wx_pay.setImageResource(R.drawable.pay_select);
                    ali_pay.setImageResource(R.drawable.select_bg);
                    type = 2;
                }
                break;
            case R.id.ali_pay:
                if (type != 1) {
                    wx_pay.setImageResource(R.drawable.select_bg);
                    ali_pay.setImageResource(R.drawable.pay_select);
                    type = 1;
                }
                break;
        }
    }

    private void showDailog() {
        if (mAertDialog == null) {
            mAertDialog = new ui.AlertDialog(RechargeActivity.this);
            mAertDialog.setDisplayMsg("其他金额", "", true);
            mAertDialog.setPositive("确定", new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    discount_10.setBackgroundResource(R.drawable.recharge);
                    discount_50.setBackgroundResource(R.drawable.recharge);
                    discount_100.setBackgroundResource(R.drawable.recharge);
                    discount_200.setBackgroundResource(R.drawable.recharge);
                    discount_500.setBackgroundResource(R.drawable.recharge);
                    discount_other.setBackgroundResource(R.drawable.recharge_bg);
                    String editMoney = mAertDialog.getEditText0().getText().toString();
                    moneyCount = Double.parseDouble(editMoney);
                    discount_other.setText(moneyCount + "");
                    mAertDialog.dismiss();
                }
            });
        }
        mAertDialog.show();
    }

    private void alipagy() {
        if(payBean==null){
            toast("数据丢失，请检查网络后重试");
            return;
        }
            Runnable payRunnable = new Runnable() {

                @Override
                public void run() {
                    // 构造PayTask 对象
                  // String order_title=getOrderInfo();
               /*  String order_title =  "_input_charset=\"utf-8\"&body=\"钱包充值\"&it_b_pay=\"30m\"&notify_url=\"http://weixin.yt1958.net:88/car-park/index.php/Home/Pay/pay_recharge_callback_alipay\"&out_trade_no=\"czg408462421250010\"&partner=\"2088101783350228\"&payment_type=\"1\"&return_url=\"m.alipay.com\"&seller_id=\"efishl@126.com\"&service=\"mobile.securitypay.pay\"&subject=\"钱包充值\"&total_fee=\"1.00\"";
                  String sign = sign(order_title);
                    try {
                        sign = URLEncoder.encode(sign);
                        Log.e("ecode",order_title);
                        order_title += "&sign=\"" + sign + "\"&" + "sign_type=\"RSA\"";
                        Log.e("bool",(sign.equalsIgnoreCase("mLImVsmalwDhTT0H%2BiVexgotjHtpNFAvBFhqqysiF6kaZcS4uYlpIaHTgstlk%2BDRDlyGfbVef7felMzH6O8PoE2HDdat798nDlQLundubBrdPKOJXNWMMwuGDEcsQjjxJYQhSXyI09z7z6r1hMxbbKaskLkMaW5d5LM3P0TkvJk%3D"))+"");
                    }catch (Exception e){
                        e.printStackTrace();
                    }*/
                   String order_title =payBean.getParamsStr()+ "&sign=\"" + payBean.getSign() + "\"&" + "sign_type=\"RSA\"";
                    PayTask alipay = new PayTask(RechargeActivity.this);
                    // 调用支付接口，获取支付结果
                    Log.e("order_title",order_title);
                    String result = alipay.pay(order_title, true);
                    Message msg = new Message();
                    msg.what = SDK_PAY_FLAG;
                    msg.obj = result;
                    mHandler.sendMessage(msg);
                }
            };
            // 必须异步调用
            Thread payThread = new Thread(payRunnable);
            payThread.start();

    }

    private void wxPay(String order_title) {
        chargeRequest2 = new HttpChargeRequest(this, 1);
        chargeRequest2.setWxPay(order_title);
        chargeRequest2.setmIHttpClinetListener(this);
        chargeRequest2.doRequest();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @SuppressWarnings("unused")
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SDK_PAY_FLAG: {
                    PayResult payResult = new PayResult((String) msg.obj);
                    /**
                     * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
                     * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
                     * docType=1) 建议商户依赖异步通知
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息

                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
                    if (TextUtils.equals(resultStatus, "9000")) {
                        toast("支付成功");
                    } else {
                        // 判断resultStatus 为非"9000"则代表可能支付失败
                        // "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
                        if (TextUtils.equals(resultStatus, "8000")) {
                            toast("支付结果确认中");
                        } else {
                            Log.e("data",resultStatus+resultInfo);
                            // 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
                            toast("支付失败");
                        }
                    }
                    break;
                }
                default:
                    break;
            }
        }
    };

    private void doAlipayRequest(String patner) {
        chargeRequest1 = new HttpChargeRequest(this, 2);
        chargeRequest1.setWxPay(patner);
        chargeRequest1.setmIHttpClinetListener(this);
        chargeRequest1.doRequest();
    }


    /**
     * create the order info. 创建订单信息
     *
     */
    private String getOrderInfo() {

        // 签约合作者身份ID
        String orderInfo = "partner=" + "\"" + payBean.getPartner() + "\"";

        // 签约卖家支付宝账号
        orderInfo += "&seller_id=" + "\"" + payBean.getSeller_id() + "\"";

        // 商户网站唯一订单号
        orderInfo += "&out_trade_no=" + "\"" + payBean.getOut_trade_no() + "\"";

        // 商品名称
        orderInfo += "&subject=" + "\"" + payBean.getSubject() + "\"";

        // 商品详情
        orderInfo += "&body=" + "\"" + payBean.getBody() + "\"";

        // 商品金额
        orderInfo += "&total_fee=" + "\"" + payBean.getTotal_fee() + "\"";

        // 服务器异步通知页面路径
        orderInfo += "&notify_url=" + "\"" + payBean.getNotify_url() + "\"";

        // 服务接口名称， 固定值
        orderInfo += "&service=\"mobile.securitypay.pay\"";

        // 支付类型， 固定值
        orderInfo += "&payment_type=\"1\"";

        // 参数编码， 固定值
        orderInfo += "&_input_charset=\"utf-8\"";

        // 设置未付款交易的超时时间
        // 默认30分钟，一旦超时，该笔交易就会自动被关闭。
        // 取值范围：1m～15d。
        // m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
        // 该参数数值不接受小数点，如1.5h，可转换为90m。
        orderInfo += "&it_b_pay=\"30m\"";

        // extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
        // orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

        // 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
        orderInfo += "&return_url=\"m.alipay.com\"";

        // 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
        // orderInfo += "&paymethod=\"expressGateway\"";
        return orderInfo;
    }

}
